/*
 * fout.c
 * Asif Shahidullah
 *
 * Handles file output operations, printing the formatted
 * output string as: 
 * 	HH:MM	TT.TT	X
 */

#include <stdio.h>

#include "d_list.h"
#include "list_data.h"
#include "fout.h"

/* Open the output file, returns the file pointer
 * on success. */
static __inline__ FILE * open_file (char *);


int write_output (List list, char *file) {
	FILE *f_handle;
	int i;
	Node curr;

	/* Handle the file opening and closing operations within
	 * the function, so potentially volatile files are not kept
	 * open longer than necessary. */
	if ((f_handle = open_file (file)) == NULL) {
		fprintf (stderr, "Failed to create/truncate output file.\n");
		return -1;
	}

	if (list->size < 1) {
		fprintf (stderr, "Attmpted write_output with list size < 1.\n");
		return -1;
	}

	curr = list->head;
	for (i = 0; i < list->size; i++) {
		/* Formatted output string: */
		fprintf (f_handle, "%02d:%02d\t%2.2f\t%d\n",
			curr->data->hour,
			curr->data->min,
			curr->data->temp,
			curr->data->ac);
		curr = curr->next;
	}

	fclose (f_handle);	
	return i;
}


FILE * open_file (char *file) {
	/* We open it with the "w" flag so it will either
	 * create or truncte a file. */
	return fopen (file, "w");
}
